function isRequiredParams(arr, data = {}) {
  if (!data) {
    return {
      err: true,
      msg: arr.join("、") + "是必传字段",
    };
  }
  const hasNo = [];
  arr.forEach((item) => {
    if (data[item] == undefined) {
      hasNo.push(item);
    }
  });
  if (hasNo.length !== 0) {
    return {
      err: true,
      msg: hasNo.join("、") + "是必传字段",
    };
  }
  return {
    err: false,
    msg: "",
  };
}

async function doSqlMiddle(fn = async () => {}) {
  try {
    const res = await fn();
    return res;
  } catch (err) {
    console.error(err);
    return {
      err: true,
    };
  }
}

function readFileName(path, filter = ["index.js"]) {
  const fs = require("fs");
  const res = fs.readdirSync(path);
  return res.filter((item) => !filter.includes(item));
}

/**
 * 将字符串序列化
 * @param data
 * @returns
 */
function JSONParse(data) {
  try {
    return JSON.parse(data);
  } catch {
    return data;
  }
}

/**
 * 将json数据字符串化
 * @param data
 * @returns
 */
function JSONStringify(data) {
  if (typeof data === "string") {
    return data;
  }
  try {
    return JSON.stringify(data);
  } catch {
    return "";
  }
}

module.exports = {
  isRequiredParams,
  doSqlMiddle,
  readFileName,
  JSONParse,
  JSONStringify,
};
